package cart;

import Entity.Product;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.*;

@WebServlet("/getShopItem")
public class GetShopItemServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 设置返回格式为 JSON
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // Map 用于按类别分组，key 为类别名称，value 为该类别下的产品列表
        Map<String, List<Product>> data = new LinkedHashMap<>();

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        String sql = "SELECT p.id, p.name, p.price, p.image_url, c.name AS category_name " +
                "FROM product p JOIN category c ON p.category_id = c.id " +
                "ORDER BY c.id, p.id";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DBUtil.getConnection();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double price = rs.getDouble("price");
                String imageUrl = rs.getString("image_url");
                String category = rs.getString("category_name");

                Product product = new Product(id, name, price, imageUrl);

                // 将产品按类别归类
                if (!data.containsKey(category)) {
                    data.put(category, new ArrayList<>());
                }
                data.get(category).add(product);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("{\"error\":\"查询产品数据出错\"}");
            return;
        } finally {
            try { if (rs != null) rs.close(); } catch (SQLException e) {}
            try { if (ps != null) ps.close(); } catch (SQLException e) {}
            try { if (conn != null) conn.close(); } catch (SQLException e) {}
        }

        // 使用 Gson 将 Map 转换为 JSON 字符串
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(data);
        out.write(json);
    }

}
